package com.cskaoyan.service.admin;

import com.cskaoyan.bean.MarketAd;
import com.cskaoyan.bean.MarketAdExample;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.MarketAdMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author by yxy_8175@163.com
 * @Description TODO
 * @Date 2022-11-19 16:01
 */

@Service
public class AdvertisementServiceImpl implements AdvertisementService {

    @Autowired
    MarketAdMapper marketAdMapper;

    @Override
    public CommonData<MarketAd> selectAllAds(BasePageInfo info,String name,String content) {

        // 开启分页
        PageHelper.startPage(info.getPage(), info.getLimit());

        MarketAdExample example = new MarketAdExample();
        MarketAdExample.Criteria criteria = example.createCriteria();

        if (name != null){
            criteria.andNameLike("%"+name+"%");
        }
        if (content != null){
            criteria.andContentLike("%"+content+"%");
        }
        criteria.andDeletedEqualTo(false);

        // List<MarketAdList> list = marketAdMapper.selectAllAds(info);
        List<MarketAd> list = marketAdMapper.selectByExample(example);

        PageInfo<MarketAd> pageInfo = new PageInfo<>(list);

        return CommonData.data(pageInfo);
    }

    @Transactional
    @Override
    public MarketAd insetAd(MarketAd ad) {
        ad.setAddTime(new Date());
        ad.setUpdateTime(new Date());
        // 插入广告信息
        marketAdMapper.insertSelective(ad);
        // 获取插入广告的主键id
        Integer id = ad.getId();
        // 根据主键id查询
        return  marketAdMapper.selectByPrimaryKey(id);
    }

    @Override
    public int deleteAdInfo(MarketAd ad) {
        // Integer id = ad.getId();
        // 直接修改delete字段  逻辑删除
        ad.setDeleted(true);
        int i = marketAdMapper.updateByPrimaryKeySelective(ad);
        // 实际删除
        // int i = couponMapper.deleteByPrimaryKey(id);
        if (i > 0){
            return BaseRespVo.STATUS_OK;
        }
        return BaseRespVo.STATUS_DELETE_FAILED;
    }

    @Override
    public MarketAd updateAdInfo(MarketAd ad) {
        // 修改时间
        ad.setUpdateTime(new Date());

        marketAdMapper.updateByPrimaryKeySelective(ad);

        return marketAdMapper.selectByPrimaryKey(ad.getId());
    }


}
